<?php
require 'vendor/autoload.php';

use think\Template;

$config = require_once './config.php';
$viewConfig = $config['view'];
$filename = $config['mysql_log'];


$template = new Template($viewConfig);


if (isset($_GET['act']) && $_GET['act'] == 'del') {
    $ret = del($filename);
} else {
    //die("123");
    $ret = show($filename);
}
$template->fetch('sql/index',['data'=>$ret,'action'=>'sql']);

//清空日志
function del($filename)
{
    $fp = @fopen($filename, "w+"); //打开文件指针，创建文件
    if (!is_writable($filename)) {
        $ret = [
            'errcode' => 1,
            'act' => 'del',
            'msg' => "log文件:" . $filename . "不可写，请检查！ 或尝试删除log文件 , 重启mysql",
            'data' => ""
        ];
    } else {
        fwrite($fp, "\r\n");

        $ret = [
            'errcode' => 0,
            'act' => 'del',
            'msg' => "清空成功",
            'data' => ""
        ];
    }
    @fclose($fp); //关闭指针
    return $ret;
}

function show($filename)
{
    $start_time = microtime(true);
    $sqlStr = "";
    if (!file_exists($filename)) {
        return [
            'errcode' => 1,
            'act' => 'refresh',
            'msg' => "log文件不存在, 请到config.php 文件中配置",
            'data' => ""
        ];
    } else {
        if (abs(filesize($filename) > (1024 * 1014 * 1))) // 1M
        {
            file_put_contents($filename, "");
            return [
                'errcode' => 1,
                'act' => 'refresh',
                'msg' => "日志文件过大，请重新请求后再次刷新",
                'data' => ""
            ];
        }
        $fp = @fopen($filename, "r") or exit("log文件打不开!"); //打开文件指针，创建文件

        while (!feof($fp)) {
            $str = fgets($fp);
            if ($str == "") {
                continue;
            }
            $str = preg_replace('/([0-9]{1,} Query)|([0-9]{1,} Quit)/', "", $str);
            $str = preg_replace('/([0-9]{1,})\sInit/', "Init", $str);
            $sqlStr .=  '<p>' . $str . '</p>';
        }

        @fclose($fp);  //关闭指针

    }

    $end_time = microtime(true);
    $interval = $end_time - $start_time;
    return [
        'errcode' => 0,
        'act' => 'refresh',
        'msg' => "成功获取",
        'data' => $sqlStr
    ];
    //echo $str = htmltag('p', 'padding:2px;color:#8B0000;font-size:14px', '获取花费:' . $interval . '秒');

}

